package com.lc.tool;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;

/**
 * Created by zhou-yb on 16/10/21.
 */

public class Convert {
    /**
     * 16进制数据转字符串格式
     * @param b 需要转换的16进制数据
     * @param len 需要转换的数据长度
     * @return 转换后的字符串
     */
    public static String HexToString(byte[] b, int len) {
        StringBuffer result = new StringBuffer();
        String hex;
        for (int i = 0; i < len; i++) {
            hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            result.append(hex.toUpperCase());
        }
        return result.toString();
    }

    /**
     * 将数组转换为字符串
     */
    public static String ArrayToString(byte[] buff) {
        String str = new String(buff);
        return str.trim();
    }

    /**
     * 将数组转换为字符串
     */
    public static String ArrayToString(char[] buff) {
        String str = new String(buff);
        return str.trim();
    }

    /**
     * 将数组转换为字符串
     */
    public static String ArrayToString(byte[] buff, String encode) {
        String str = "";
        try {
            str = new String(buff, encode);
        } catch (UnsupportedEncodingException e) {
        }
        return str.trim();
    }

    /**
     * 16进制数据转字符串格式
     * @param b 需要转换的16进制数据
     * @return 转换后的字符串
     */
    public static String HexToString(byte[] b) {
        return HexToString(b, b.length);
    }

    /**
     * 将16进制格式的字符串转换为对应的16进制数据
     * @param src 需要转换的字符串
     * @return 转换后的16进制数据数组
     */
    public static byte[] StringToHex(String src) {
        String str = src.trim();
        int l = str.length() / 2;
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++) {
            ret[i] = (byte) Integer
                    .valueOf(str.substring(i * 2, i * 2 + 2), 16).byteValue();
        }
        return ret;
    }

    /**
     * 格式化异常信息
     * @param e 需要格式化的异常
     * @return 格式化后的字符串
     */
    public static String FormatExceptionMSG(Throwable e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        String errMsg = sw.toString();
        return errMsg;
    }
}
